<!-- 文件导入 -->
<template>
  <div>
    <el-dialog :before-close="handleClose" title="导入excel数据" :visible.sync="uploadDialog" width="400px" modal:false :close-on-click-modal="false">
      <el-row>
        <el-col :span="24">
          <el-upload class="upload-cloud" drag ref="uploadExcel" :headers="token" :on-success="uploadSuccess" :auto-upload="false" 
          :limit="1" accept=".xlsx,.xls" :on-change="onExcelSelected" :file-list="excelList" :action="baseURL + '/socialized-market/marketQuotation/excellmport'">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              请上传 excel 的 xlsx/xls 类型文件,请勿上传其他非excle文件！
            </div>
          </el-upload>
        </el-col>
      </el-row>

      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadDialog = false;initImportPage();">取 消</el-button>
        <el-button type="primary" @click="sureImportHandle">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 导入失败时提示 :before-close="handleClose"-->
    <el-dialog :close-on-click-modal="false" title="导入失败" :visible.sync="dialogVisible" width="30%">
      <span style="color:red;line-height:20px">导入失败，是否下载错误提示文件?</span>
      <div>用于告知当前导入文件的具体错误情况</div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="downFile">下载错误提示文件</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import Cookies from "js-cookie";

export default {
  data() {
    return {
      url:null,
      baseURL: "http://fishery.ssagroup.cn:9091",
      // baseURL: "http://192.168.20.123:9090",
      uploadDialog: false,
      preExcelData: [],
      excelList: [],
      token: {
        token: localStorage.getItem("token"),
      },
      currentMarketId: null, // 当前下载的marketId
      dialogVisible: false,  // 导入错误提示框
      errorExcle: "",        // 导入错误时，返回的需要下载的excle
      rowMarket: {},         // 当前导入行的市场信息
    };
  },
  methods: {
    init(row) {
      this.uploadDialog = true;
      this.fileList = [];
      if (!row) {
        console.log('row不存在!!!');
        // this.currentMarketId=null
        this.url=this.baseURL + `/socialized-market/marketQuotation/excelImport`
      }else{
        console.log('row存在');
        this.currentMarketId = row.market.marketId;
        this.url=this.baseURL + `/socialized-market/marketQuotation/excelImport?marketId=${this.currentMarketId}`
        console.log('this.currentMarketIdthis.currentMarketId',this.currentMarketId);
      }
      this.rowMarket = row;
      console.log("当前导入行的市场信息", this.rowMarket);
    },
    uploadSuccess(data) {
      const that = this;
      that.excelList.length = 0;
      console.log(data);
      that.$refs.uploadExcel.clearFiles();
      if (data.code === 0) {
        that.preExcelData = data.data;
      } else {
        this.$notify.error({ title: "错误", message: data.msg });
        return;
      }
    },
    onExcelSelected(file) {
      if (file && file.status === "ready") {
        this.excelList.length = 0;
        this.$refs.uploadExcel.clearFiles();
        this.excelList.push(file);
      }
    },

    sureImportHandle() {
      console.log("excelList", this.excelList);
      if (this.excelList.length === 0) {
        this.$notify.error({ title: "错误", message: "请上传excel表格" });
        return false;
      }
      let formData = new FormData();
      console.log(formData);
      formData.append("excel", this.excelList[0].raw);
      // axios({
      //   method:'post',url:this.baseURL + `/socialized-market/marketQuotation/excelImport?marketId=${this.currentMarketId}`,
      //   formData,
      //   responseType:"arraybuffer",
      //     headers: {token: Cookies.get("token")},
      // })
      // ,
      axios
        .post(
          // this.baseURL + `/socialized-market/marketQuotation/excelImport`,
          // this.baseURL + `/socialized-market/marketQuotation/excelImport?marketId=${this.currentMarketId}`,
          this.url,
          formData,
          {
            headers: { token: Cookies.get("token") },
            responseType: "blob",
            // responseType: "arraybuffer"
          }
        )
        .then((res) => {
          console.log("导入文件时的res", res);
          // 返回excle错误文件
          if (res.data.type !== "application/json") {
            this.errorExcle = res.data; // 返回的excle
            this.dialogVisible = true;
          }
          // 将返回数据解析成JSON格式；
          res.data.text().then((text) => {
            const json = JSON.parse(text);
            // console.log("res.data转换json+++++++++++", json);
            // 导入成功
            if (res.data.type == "application/json" && json.code == 200) {
              this.$notify.success({ title: "成功", message: "导入成功" });
              this.uploadDialog = false;
              this.$emit("refresh");
              this.initImportPage();
            }
            // 报错提示
            if (res.data.type == "application/json" && json.code == 500) {
              this.$notify.error({ title: json.msg, message: res.statusText });
            }
          });
        })
        .catch((err) => {
          console.log(err);
        });
    },
    initImportPage() {
      this.excelList = [];
      this.uploadDialog = false;
      this.$refs.uploadExcel.clearFiles();
    },
    // 导入弹窗关闭前回调
    handleClose(done) {
      this.$refs.uploadExcel.clearFiles();
      done();
    },
    // 下载错误提示的的数据；
    downFile() {
      let url = window.URL.createObjectURL(
        new Blob([this.errorExcle], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"})
      );
      let link = document.createElement("a"); // 创建a标签来下载
      link.style.display = "none";
      link.href = url;
      if (!this.currentMarketId) {
        link.setAttribute("download",`错误模板`);
      }else{
        link.setAttribute("download",`导入至 "${this.rowMarket.market.name}"  返回的错误模板`);
      }
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      this.dialogVisible = false;
    },
  },
};
</script>

<style scoped>
/* 文件类型提示 */
.el-upload__tip {
  color: red;
}
</style>
